<template>
    <div class="main-container">
        <div class="text">
            商品分类
            <el-button class="fl" type="primary" @click="openEditDialog()">添加分类</el-button>
        </div>
        <el-table :data="tableData" style="width: 100%">
            <el-table-column label="序号" prop="id" />
            <el-table-column label="分类名">
                <template #default="scope">
                    <span v-if="editingRowId !== scope.row.id">{{ scope.row.cateName }}</span>
                    <el-input v-model="scope.row.cateName" placeholder="请输入分类名" v-else />
                </template>
            </el-table-column>
            <el-table-column label="是否启用">
                <template #default="scope">
                    <el-switch v-model="scope.row.state" :disabled="editingRowId !== scope.row.id" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)" v-if="editingRowId !== scope.row.id">
                        编辑
                    </el-button>
                    <el-button size="small" type="success" @click="handleSave(scope.row)" v-else>
                        保存
                    </el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="demo-pagination-block">
            <!-- <div class="demonstration">All combined</div> -->
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
                :size="size" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="onPageSizeChange"
                @current-change="onPageChange" />
        </div>
        <!-- 新增类别 -->
        <el-dialog v-model="editDialogVisible" title="新增类别" width="40%">
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="分类名称">
                    <el-input v-model="editForm.cateName" placeholder="请输入分类名称" />
                </el-form-item>
                <el-form-item label="是否启用">
                    <el-switch v-model="editForm.state" />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">确认</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { catelist, editcate, delcate, addcate } from '@/api/goods';

interface Category {
    id: number;
    cateName: string;
    state: number;
}
const editForm = ref<Category>({
    id: 0,
    cateName: '',
    state: 0,
});

const tableData = ref<Category[]>([]); // 存储表格数据
const currentPage = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const total = ref(0); // 总条数
const editingRowId = ref<number | null>(null); // 当前正在编辑的行的 ID
const editDialogVisible = ref(false);
// 获取数据的函数
const fetchTableData = async () => {
    try {
        await catelist(
            {
                currentPage: currentPage.value, // 当前页码
                pageSize: pageSize.value, // 每页条数
            }
        ).then((response) => {
            // 处理数据，将 state 转换为布尔值
            tableData.value = response.data.map((item: Category) => ({
                ...item,
                state: item.state === 1, // 转换为布尔值
            }));
            total.value = response.total;
        });
    } catch (error) {
        console.error('Failed to fetch table data:', error);
    }
};

// 添加按钮点击事件
const openEditDialog = () => {
    editDialogVisible.value = true; // 打开新增类别对话框
};

const handleAdd = async () => {
    try {
        await addcate(
            {
                cateName: editForm.value.cateName,
                state: editForm.value.state,
            }
        ).then((response) => {
            ElMessage.success('添加成功');

            editDialogVisible.value = false; // 关闭对话框
            fetchTableData(); // 刷新数据
        });
    } catch (error) {
        ElMessage.error('添加失败');
        console.error('Add failed:', error);
    } finally {
        editForm.value.cateName = ''; // 清空输入框
        editForm.value.state = 0; // 重置状态
    }
};
// 编辑按钮点击事件
const handleEdit = (row: Category) => {
    editingRowId.value = row.id; // 设置当前编辑的行 ID
};

// 保存按钮点击事件
const handleSave = async (row: Category) => {
    console.log('保存修改:', row);

    await editcate({
        id: row.id,
        cateName: row.cateName,
        state: row.state,
    },
    ).then(
        response => {
            ElMessage.success('修改成功')
            console.log('Edit successful:', row)
            editingRowId.value = null // 退出编辑状态
            fetchTableData() // 刷新数据
        }).catch(error => {
            ElMessage.error('修改失败')
            console.error('Edit failed:', error)
        })
};

// 删除按钮点击事件
const handleDelete = async (row: Category) => {
    console.log('删除:', row);
    try {
        await delcate(
            {
                id: row.id,
            }
        ).then(
            response => {
                ElMessage.success('删除成功')
                fetchTableData(); // 重新获取数据
            })

    } catch (error) {
        console.error('Failed to delete:', error);
    }
};

// 分页事件处理
const onPageChange = (page: number) => {
    currentPage.value = page;
    fetchTableData(); 
};

const onPageSizeChange = (size: number) => {
    pageSize.value = size;
    fetchTableData(); 
};

// 在组件挂载时获取数据
onMounted(() => {
    fetchTableData();
});
</script>

<style scoped>
.text {
    width: 100%;
    height: 50px;
    border-bottom: 2px solid #f0f2f5;
    margin-bottom: 20px;
    font-size: 20px;
    line-height: 50px;
    display: flex;
    justify-content: space-between;
}

.fl {
    background: #ffffff;
    color: #000;
    border: 2px solid #f0f2f5;
    height: 40px;
    margin-right: 10px;
}
</style>